package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class DIshServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    /**
     * 新增菜品
     * @param dto
     */
    @Override
    @Transactional//开启事务管理
    public void insert(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);

        dishMapper.insert(dish);

        Long id = dish.getId();
        List<DishFlavor> flavors = dto.getFlavors();
        if(!CollectionUtils.isEmpty(flavors)){
            flavors.forEach(i -> {
                i.setDishId(id);
            });
            dishFlavorMapper.insertBatch(flavors);
        }


    }

    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult list(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page page = dishMapper.list(dto);

        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @Transactional//开启事务
    public void deleteBatch(List<Long> ids) {
        //菜品是否起售，起售不能删
        List<Dish> dishes = dishMapper.getByIds(ids);
        dishes.forEach(i -> {
            if(i.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //菜品是否关联了套餐，关联了不能删
        Integer count = dishMapper.getSetmealDish(ids);
        if(count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品
        dishMapper.deleteBatch(ids);
        //删除菜品下的口味
        dishFlavorMapper.deleteBatch(ids);
    }
    /**
     * 根据id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //查询菜品
        Dish dish = dishMapper.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        //查询菜品下的口味
        List<DishFlavor> list = dishFlavorMapper.getByDishId(id);
        dishVO.setFlavors(list);
        return dishVO;
    }

    /**
     * 修改菜品
     * @param dto
     */
    @Override
    @Transactional
    public void update(DishDTO dto) {
        //修改菜品基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.update(dish);
        //修改菜品口味信息
        List<DishFlavor> flavors = dto.getFlavors();
        //删除该菜品下的口味
        Long id = dto.getId();
        dishFlavorMapper.deleteByDishId(id);
        if(flavors == null || flavors.isEmpty()){
            return;
        }else {
            flavors.forEach(i -> i.setDishId(id));
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 更该菜品状态
     * @param id
     */
    @Override
    public void updateStatus(Integer status,Long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        //当前菜品关联的套餐是否起售
        if(Objects.equals(status,StatusConstant.DISABLE)){
           List<SetmealDish> l = setmealDishMapper.getByDishId(id);
           if(!l.isEmpty()){
               List<Long> setmealIds = l.stream().map(SetmealDish::getSetmealId).collect(Collectors.toList());
               List<Setmeal> setmeals = setmealMapper.getByIds(setmealIds);
               setmeals.forEach(i ->{
                   if(Objects.equals(i.getStatus(),StatusConstant.ENABLE)){
                       throw new SetmealEnableFailedException(MessageConstant.DISH_ENABLE_FAILED);
                   }
               });
           }
        }
        dishMapper.update(dish);
    }

    /**
     * 根据分类id查询菜品
     * @param id
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long id) {
        List<Dish> byCateGory = dishMapper.getByCateGory(id);
        return byCateGory;
    }

    /**
     * 查询菜品
     * @param categoryId
     * @return list
     */
    @Override
    public List<DishVO> getList(Long categoryId) {
        List<DishVO> list = dishMapper.getList(categoryId);
        return list;
    }


}
